package ldk.util.scrollviews

import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import org.json.JSONArray
import org.json.JSONException

/**
 * WebView 的辅助类
 * Created by ldkxingzhe@163.com on 2017/9/13.
 */
// 此方法在Load Finish之后调用
fun WebView.setOnImageClick(imageClickListener: (List<String>, Int) -> Unit){
    this.settings.javaScriptEnabled = true
    this.addJavascriptInterface(WebViewInterface(imageClickListener), "WebViewExtends")
}

fun WebView.afterFinished(){
    this.loadUrl("javascript:var setImageClickListener = function(){\n" +
            "\tif(typeof WebViewExtends == 'undefined'){\n" +
            "\t\t\tvar WebViewHelper = {\n" +
            "\t\t\t\tonClickImage: function(str, index){\n" +
            "\t\t\t\t\tconsole.log(\"需要这是对应的属性, str is \" + str + \", and index is \" + index);\n" +
            "\t\t\t\t}\n" +
            "\t\t\t};\n" +
            "\t}\n" +
            "\tconsole.log(\"调用函数\");\n" +
            "\tvar images = document.getElementsByTagName(\"img\");\n" +
            "\tvar resultImages = [];\n" +
            "\tArray.prototype.forEach.call(images, image => {\n" +
            "\t\tif(image.clientWidth >= 50 && image.clientHeight >= 50){\n" +
            "\t\t\tresultImages.push(image);\n" +
            "\t\t\tif(typeof image.onclick != \"function\"){\n" +
            "\t\t\t\timage.onclick = function(){\n" +
            "\t\t\t\t\tvar imageUrl = [];\n" +
            "\t\t\t\t\tresultImages.forEach(_image =>{\n" +
            "\t\t\t\t\t\timageUrl.push(_image.src);\n" +
            "\t\t\t\t\t});\n" +
            "\t\t\t\t\tvar index = resultImages.indexOf(this);\n" +
            "\t\t\t\t\tconsole.log(\"index is \" + index);\n" +
            "\t\t\t\t\tWebViewExtends.onClickImage(JSON.stringify(imageUrl), index);\n" +
            "\t\t\t\t}\n" +
            "\t\t\t}\n" +
            "\t\t}\n" +
            "\t});\n" +
            "};\n" +
            "setImageClickListener();")
}

class WebViewInterface(listener: (List<String>, Int) -> Unit){
    private var imageClickListener = listener;

    @JavascriptInterface
    fun onClickImage(jsonArrayString: String, index: Int) {
        try {
            val jsonArray = JSONArray(jsonArrayString)
            val imageList = ArrayList<String>()
            (0 until jsonArray.length()).mapTo(imageList) { jsonArray.getString(it) }
            if (index >= 0 && index < imageList.size){
                imageClickListener.invoke(imageList, index)
            }
        }catch (e: JSONException){
            Log.e("WebViewInterface", "jsonException ${e.message}", e)
        }
    }
}